/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月15日 上午9:09:15 
 * 
 */
package phoenics.upservice.restcontroller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import phoenics.common.BaseData.RestResp;
import phoenics.upservice.dto.UserUpdata;
import phoenics.upservice.entity.User;
import phoenics.upservice.repository.UserRepo;
import phoenics.upservice.service.SmsService;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
@RestController  
@RequestMapping("/register")
public class UserController {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);
	@Autowired
	SmsService smsService;
	 @Resource  
	 private UserRepo userRepo;
	 @Autowired
	 BCryptPasswordEncoder passwordEncoder;
	  
	    @PostMapping("/register")  
	    public RestResp register(@RequestBody UserUpdata restUser){
			String test=smsService.takeCacheSmsCode(restUser.getMobile());
			if(test==null){
				return RestResp.fail("手机注册码过期");
			}
			if(!test.equals(restUser.getMobileCode())){
				return RestResp.fail("手机注册码错误");
			}
	        return userRepo.findByMobile(restUser.getMobile()).map(u -> RestResp.fail("手机号码已经存在")).orElseGet(() -> {
	        	User user=new User();
	        	user.setMobile(restUser.getMobile());
	        	user.setPassword(passwordEncoder.encode(restUser.getPassword()));
	           User u = userRepo.save(user);  
	           logger.info("{} registered", u);  
	           return RestResp.success("注册成功");  
	        });  
	    }  
	    @PostMapping("/forget")  
	    public RestResp forget(@RequestBody UserUpdata user){
			String test=smsService.takeCacheSmsCode(user.getMobile());
			if(test==null){
				return RestResp.fail("手机注册码过期");
			}
			if(!test.equals(user.getMobileCode())){
				return RestResp.fail("手机注册码错误");
			}
	        return userRepo.findMobileCached(user.getMobile()).map(u -> {
	        	u.setPassword(passwordEncoder.encode(user.getPassword()));
	        	userRepo.save(u);
	        	return RestResp.success("密码修改成功");  
	        }).orElse(RestResp.fail("手机未注册")
	        );  
	    }
	    @GetMapping("/sms")
		public RestResp sendSms(@RequestParam(value = "phone", defaultValue = "") String phone ){
			Pattern p = Pattern.compile("^((\\+86)|(86))?[1][3456789][0-9]{9}$");
			Matcher m = p.matcher(phone);
			if(m.matches()){
				String rt=smsService.sendMessage(phone);
				if(StringUtils.isNotBlank(rt)){
					return RestResp.success("ok");
				}
			}
			return RestResp.fail();
		}
}
